
<!-- 目录 -->
<script lang="ts" setup>
import { reactive, onBeforeUnmount, onMounted } from 'vue'
import pubsub from 'pubsub-js'
import { useCommpnStore } from "@/stores/common"
const useStore = useCommpnStore()
let state: any = reactive({
    list: [],
    activeIndex: 0,
    positionLeft: '',
})

const handDir = (e: any, index: Number): void => {
    const targetPosition: any = document.querySelector(`[data-v-md-line="${e.lineIndex}"]`)
    const targetPositionTop = targetPosition.getBoundingClientRect().top

    window.scrollTo({
        top: targetPositionTop + window.scrollY,
        behavior: "smooth", // 可选，平滑滚动效果
    });

    state.activeIndex = index
}
onMounted(() => {
    pubsub.subscribe('directory', (_: any, data: any) => {
        state.list = data
        data.forEach((item: any, index: any) => {
            item.scrollTop = item.el.getBoundingClientRect().top + window.scrollY
        })
        window.addEventListener('scroll', (e) => {
            data.forEach((item: any, index: any) => {
                if (window.scrollY > item.scrollTop - 100) state.activeIndex = index
            })
        });
    })
    useStore.changePageWidth(0)
})

onBeforeUnmount(() => {
    window.removeEventListener('scroll', () => { }); // 离开当前组件移除事件监听
});

</script>

<template>
    <div class="directory-warp" :style="{ left: useStore.directoryLeft }">
        <div class="title">目录</div>
        <el-divider />
        <div class="directory">

            <div :class="{ 'dir-item': true, active: state.activeIndex === index }" @click="handDir(item, index)"
                v-for="(item, index) in state.list" :key="index">

                {{ item.title }}

            </div>

        </div>
    </div>
</template>
  
<style lang="scss" scoped>
.directory-warp {
    
    background-color: var(--c-bg-box);
    overflow: hidden;
    border-radius: 10px;
    padding: 0 !important;
    max-width: 260px;
    width: 14vw;
    position: absolute;
    top: 0;
    border: 1px solid #E6E8EB;

    &:hover {
        box-shadow: 0px 0px 20px 0px var(--c-shadow);
    }

    .title {
        font-size: 18px;
        margin: 20px;
        margin-bottom: 0;
    }

    .el-divider {
        margin: 15px 0;
    }

    .directory {
        margin: 20px;
        margin-top: 0;
        overflow-y: auto;
        max-height: 100vh;

        .dir-item {
            font-size: 14px;
            line-height: 28px;
            cursor: pointer;
            transition: all .5s;
            color: var(--c-text-2);
        }

        .active {
            color: #409eff;
        }
    }
}
</style>